package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ContractManageMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-05
 */
@Service
public class ContractManageServiceImpl implements IContractManageService
{
    @Autowired
    private ContractManageMapper contractManageMapper;

    @Autowired
    private IContractManageRelationService contractManageRelationService;
    @Autowired
    private IContractPlanAmountService contractPlanAmountService;

    @Autowired
    private IContractInvoiceService contractInvoiceService;

    @Autowired
    private IContractManageFileService contractManageFileService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public ContractManage selectContractManageById(Long id)
    {
        ContractManage contractManage = contractManageMapper.selectContractManageById(id);
        String fileData = contractManage.getFileData();
        //附件格式处理
        if(StringUtils.isNotEmpty(fileData)){
            String[] split = StringUtils.split(fileData,",");
            List<Map<String,String>> list = new ArrayList<>();
            Map<String,String> fileMap;
            List<String> fileList = new ArrayList();
            for (String ids : split) {
                ContractManageFile manageFile = contractManageFileService.selectContractManageFileById(Long.valueOf(ids));
                String file = manageFile.getFilePath();
                fileMap = new HashMap<>();
                String name = file.substring(file.lastIndexOf("/")+1,file.length());
                fileMap.put("name",name);
                fileMap.put("url",file);
                fileList.add(file);
                list.add(fileMap);
            }
            if(CollectionUtils.isNotEmpty(fileList)){
                contractManage.setFileNameList(fileList);
            }
            if(CollectionUtils.isNotEmpty(list)){
                contractManage.setFileList(list);
            }
        }
        List<ContractManageRelation> contractManageRelations = contractManageRelationService.selectContractManageRelationByContractId(id);
        if(CollectionUtils.isNotEmpty(contractManageRelations)){
            List<Long> collect = contractManageRelations.stream().map(e -> e.getContractRelationId()).collect(Collectors.toList());
            contractManage.setManageDataList(collect);
        }

        return contractManage;
    }

    /**
     * 删除关联合同
     * @param relation
     * @return
     */
    @Override
    public int deleteContractRelations(ContractManageRelation relation){
        return contractManageRelationService.deleteContractManageRelationData(relation);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param contractManage 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<ContractManage> selectContractManageList(ContractManage contractManage)
    {
        return contractManageMapper.selectContractManageList(contractManage);
    }
    @Override
    public List<ContractManage> selectManageListByProjectId(ContractManage contractManage)
    {
        return contractManageMapper.selectManageListByProjectId(contractManage);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param contractManage 【请填写功能名称】
     * @return 结果
     */
    @Transactional
    @Override
    public int insertContractManage(ContractManage contractManage)
    {
        Long id = contractManageMapper.selectContractManageByMaxId();
        contractManage.setId(id == null ? 1 : id + 1);
        //设置文件信息
        contractManage.setCreateTime(DateUtils.getNowDate());
        List<Long> manageDataList = contractManage.getManageDataList();
        if(CollectionUtils.isNotEmpty(manageDataList)){
            ContractManageRelation contractManageRelation = null;
            for (Long ids : manageDataList) {
                //设置管理合同信息
                contractManageRelation =new ContractManageRelation();
                contractManageRelation.setContractId(contractManage.getId());
                contractManageRelation.setContractRelationId(ids);
                contractManageRelationService.insertContractManageRelation(contractManageRelation);

                //设置关联合同的附件信息
                List<ContractManageFile> manageFiles = contractManageFileService.selectContractManageFileByManageId(ids);
                if(CollectionUtils.isNotEmpty(manageFiles)){
                    List<String> fileNameList = contractManage.getFileNameList();
                    if(fileNameList == null){
                        fileNameList = new ArrayList<>();
                    }
                    for (ContractManageFile file : manageFiles) {
                        String path = file.getFilePath();
                        fileNameList.add(path);
                    }
                    contractManage.setFileNameList(fileNameList);
                }
            }
        }
        setFile(contractManage);
       return contractManageMapper.insertContractManage(contractManage);
    }

    /**
     * 设置文件列表
     * @param contractManage
     */
    private void setFile(ContractManage contractManage) {
        List<String> fileNameList = contractManage.getFileNameList();
        if(CollectionUtils.isNotEmpty(fileNameList)){
            StringJoiner joiner = new StringJoiner(",");
            for (String s : fileNameList) {

                ContractManageFile contractManageFile = new ContractManageFile();
                contractManageFile.setFilePath(s);
                contractManageFile.setManageId(contractManage.getId());
                List<ContractManageFile> manageFiles = contractManageFileService.selectContractManageFileList(contractManageFile);
                //不存在则新增
                if(CollectionUtils.isEmpty(manageFiles)){
                    /**
                     * 存放合同文件库表信息
                     */
                    contractManageFile = new ContractManageFile();
                    contractManageFile.setManageId(contractManage.getId());
                    contractManageFile.setFilePath(s);
                    contractManageFileService.insertContractManageFile(contractManageFile);

                    joiner.add(contractManageFile.getId()+"");
                }else{
                    joiner.add(manageFiles.get(0).getId()+"");
                }
            }
            contractManage.setFileData(joiner.toString());
        }else{
            contractManage.setFileData("");
        }
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param contractManage 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateContractManage(ContractManage contractManage)
    {
        contractManage.setUpdateTime(DateUtils.getNowDate());
        //删除关联关系
       // contractManageRelationService.deleteContractManageRelationByContractId(contractManage.getId());
        List<Long> manageDataList = contractManage.getManageDataList();
        if(CollectionUtils.isNotEmpty(manageDataList)){
            Long id = contractManage.getId();
            ContractManageRelation contractManageRelation = null;
            for (Long ids : manageDataList) {
                //设置管理合同信息
                contractManageRelation =new ContractManageRelation();
                contractManageRelation.setContractId(contractManage.getId());
                contractManageRelation.setContractRelationId(ids);
                List<ContractManageRelation> relations = contractManageRelationService.selectContractManageRelationList(contractManageRelation);
                if(CollectionUtils.isEmpty(relations)){
                    contractManageRelationService.insertContractManageRelation(contractManageRelation);
                }

                //设置关联合同的附件信息
                List<ContractManageFile> manageFiles = contractManageFileService.selectContractManageFileByManageId(ids);
                if(CollectionUtils.isNotEmpty(manageFiles)){
                    List<String> fileNameList = contractManage.getFileNameList();
                    if(fileNameList == null){
                        fileNameList = new ArrayList<>();
                    }
                    for (ContractManageFile file : manageFiles) {
                        String path = file.getFilePath();
                        //不包含此文档时 需要添加包含时不添加
                        if(!fileNameList.contains(path)){
                            fileNameList.add(path);
                        }
                    }
                    contractManage.setFileNameList(fileNameList);
                }
            }
        }
        setFile(contractManage);
        return contractManageMapper.updateContractManage(contractManage);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteContractManageByIds(Long[] ids)
    {
        //删除文件信息
        for (Long id : ids) {
            List<ContractManageRelation> relations = contractManageRelationService.selectContractManageRelationByContractRelationId(id);
            if(CollectionUtils.isNotEmpty(relations)){
                throw new RuntimeException("该合同有被关联，无法删除。");
            }
            contractManageFileService.deleteContractManageFileByManageId(id);
        }
        return contractManageMapper.deleteContractManageByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteContractManageById(Long id)
    {
        return contractManageMapper.deleteContractManageById(id);
    }

    /**
     * 查询合同关联信息
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> selectContractRelationById(Long id){
        Map<String,Object> resultMap = new HashMap<>();
        //查询关联合同信息
        List<ContractManage> contractManages = contractManageMapper.selectContractRelationById(id);
        resultMap.put("contract",contractManages);
        //查询账款计划信息
        List<ContractPlanAmount> contractPlanAmounts = contractPlanAmountService.selectContractPlanAmountByContractId(id);
        resultMap.put("planAmounts",contractPlanAmounts);

        //查询发票信息
        List<ContractInvoice> contractInvoices = contractInvoiceService.selectContractInvoiceByContractId(id);
        resultMap.put("invoices",contractInvoices);

        return resultMap;
    }

    /**
     * 查询合同总数
     * @return
     */
    @Override
    public Map<String, Object> selectContractTotal(ContractManage contractManage) {
        return contractManageMapper.selectContractTotal(contractManage);
    }

    /**
     * 收入合同数量
     * @return
     */
    @Override
    public List<Map<String, Object>> selectIncomeContractNum(ContractManage contractManage) {
        return contractManageMapper.selectIncomeContractNum(contractManage);
    }

    /**
     * 支出合同数量
     * @return
     */
    @Override
    public List<Map<String, Object>> selectExpenditureContractNum(ContractManage contractManage) {
        return contractManageMapper.selectExpenditureContractNum(contractManage);
    }

    /**
     * 收入合同金额
     * @return
     */
    @Override
    public List<Map<String, Object>> selectIncomeContractAmount(ContractManage contractManage) {
        return contractManageMapper.selectIncomeContractAmount(contractManage);
    }

    /**
     *  支出合同金额
     * @return
     */
    @Override
    public List<Map<String, Object>> selectExpenditureContractAmount(ContractManage contractManage) {
        return contractManageMapper.selectExpenditureContractAmount(contractManage);
    }

    /**
     *  查询收款和付款数据
     *  1 实际回款 2计划回款
     * @return
     */
    @Override
    public List<Map<String, Object>> selectCollectionAndPlanData(ContractManage contractManage) {
        return contractManageMapper.selectCollectionAndPlanData(contractManage);
    }

    /**
     *   查询收款和付款数据
     *   1 实际付款 2计划付款
     * @return
     */
    @Override
    public List<Map<String, Object>> selectPaymentAndPlanData(ContractManage contractManage) {
        return contractManageMapper.selectPaymentAndPlanData(contractManage);
    }

    @Override
    public List<Map<String, Object>> selectInvoiceData(ContractManage contractManage) {
        return contractManageMapper.selectInvoiceData(contractManage);
    }
}
